package cn.scw.project.separate.controller;

import cn.scw.common.constant.Constants;
import cn.scw.common.exception.CustomException;
import cn.scw.common.separate.SeparateMethod;
import cn.scw.common.separate.model.RegisterModel;
import cn.scw.common.separate.response.BaseResponse;
import cn.scw.common.utils.StringUtils;
import cn.scw.common.utils.ZipUtils;
import cn.scw.framework.manager.AsyncManager;
import cn.scw.project.separate.domain.SaUser;
import cn.scw.project.separate.domain.SaUserImg;
import cn.scw.project.separate.service.SaUserImgService;
import cn.scw.project.separate.service.SaUserService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;

@Component
public class AsyncTask {

    @Resource
    private SaUserImgService saUserImgService;

    @Resource
    private SeparateMethod separateMethod;

    @Resource
    private SaUserService saUserService;

    private int i = 0;

    /**
     * 注册商户
     *
     * @param user
     */
    public void submitRegister(SaUser user, SaUserImg saUserImg) {
        i++;
        System.out.println("注册进件商户事务处理" + i);
        String requestId = user.getId() + "_" + System.currentTimeMillis();
        SaUser saUser = saUserService.select(user.getId());
        if (saUser.getState().compareTo(0) == 0) {
            System.out.println("注册进件商户事务处理_" + requestId);
            //调用随身付注册商户接口
            //图片打包上传
            String filePath = Constants.UPLOAD_FILE + "/upload/store/" + user.getId();
            File file = new File(filePath);
            if (!file.exists()) file.mkdirs();
            ZipUtils.zip(filePath, "imageCode");
            String fileCode = separateMethod.updateFile(filePath + "/imageCode.zip", StringUtils.isBlank(saUserImg.getFileCode()) ? "" : saUserImg.getFileCode());
            saUserImg.setFileCode(fileCode);
            saUserImgService.save(saUserImg);

            registerAccount(user, saUserImg, requestId);
        }
    }

    private void registerAccount(SaUser user, SaUserImg saUserImg, String requestId) {
        if (StringUtils.isNotBlank(saUserImg.getFileCode())) {
            RegisterModel registerModel = JSONObject.parseObject(JSONObject.toJSONString(user), RegisterModel.class);
            registerModel.setRequestId(requestId);
            registerModel.setFileCode(saUserImg.getFileCode());
            registerModel.setStmManIdNo(user.getStmManIdMo());
            BaseResponse response = separateMethod.registerAccount(registerModel);
            if (!response.getSuccess()) {
                //提交失败
                user.setState(99);
                user.setErrMsg(response.getRetMsg());
                saUserService.save(user);
            }
        }
    }
}
